package com.xyxy.platform.openapi.trade.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.xyxy.platform.modules.core.utils.ResponseUtils;
import com.xyxy.platform.modules.core.web.controller.BaseController;
import com.xyxy.platform.modules.core.web.response.ResponseMessage;
import com.xyxy.platform.modules.entity.trade.Goods;
import com.xyxy.platform.modules.entity.trade.OrderComment;
import com.xyxy.platform.modules.entity.trade.OrderInfo;
import com.xyxy.platform.modules.service.trade.GoodsService;
import com.xyxy.platform.modules.service.trade.OrderCommentService;
import com.xyxy.platform.modules.service.trade.OrderService;
import com.xyxy.platform.modules.service.trade.vo.Order;
import com.xyxy.platform.modules.service.trade.vo.OrderCommentDto;
import com.xyxy.platform.openapi.utils.ResultCodeEnum;

/** 
 * 订单控制器
 * @author vic E-mail: 251361939@qq.com
 * @version 创建时间：2015年12月19日 下午6:10:20 
 */
@RestController
@RequestMapping("/app/v1")
public class OrderController extends BaseController {
	
	final Logger logger = LoggerFactory.getLogger(OrderController.class);
	final SimpleDateFormat fullSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	@Autowired
	private OrderService orderService;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private OrderCommentService orderCommentService;
	
	/**
	 * 订单列表
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "order/order_list", method = RequestMethod.POST)
	public  ResponseMessage<?>  orderList(){
		boolean success = false;
		String msg = null ;
		ResultCodeEnum code = ResultCodeEnum.ERROR;
		List<Order> result = null;
		
		String typeStr = request.getParameter("type");
		String pageStr = request.getParameter("page");
		String rowsStr = request.getParameter("rows");
		String optionStr  = request.getParameter("option");
		String memberId = null; //拦截器根据token，会员名称获取会员id并输入至memberId
		
		int type = 0;
		if(!StringUtils.isEmpty(typeStr)){
			try{
				type = Integer.parseInt(typeStr);
				if( type < 0 || type > 7){
					code = ResultCodeEnum.PARD_BREAK;
					logger.info("type value error");
					return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
				}
			}catch(Exception e){
				e.printStackTrace();
				logger.info("type parseInt error");
				return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
			}
		}
		
		
		if(StringUtils.isEmpty(memberId)){
			code = ResultCodeEnum.PARD_BREAK;
			logger.info("memberId isEmpty");
			return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
		}
		
		if(StringUtils.isEmpty(optionStr)){
			code = ResultCodeEnum.PARD_BREAK;
			logger.info("option isEmpty");
			return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
		}
		
		int option = 0;
		try{
			option = Integer.parseInt(optionStr);
		}catch(Exception e){
			e.printStackTrace();
			code = ResultCodeEnum.PARD_BREAK;
			logger.info("option parseInt error");
			return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
		}
		
		
		int page  = 1;
		int rows  = 10;
		if(!StringUtils.isEmpty(pageStr)){
			page = Integer.parseInt(pageStr);
			page = page<0?1:page;
		}
		if(!StringUtils.isEmpty(rowsStr)){
			rows = Integer.parseInt(rowsStr);
			rows = rows<0?1:rows;
			rows = rows>100?100:rows;
		}
		
		List<OrderInfo> orderInfoList = orderService.findOrderInfoList(option, memberId, typeStr , page, rows);
		if(orderInfoList!=null&&orderInfoList.size()>0){
			result = new ArrayList<Order>();
			Order order = null;
			String imgurl = "";
			String alias  = "";
			int gender = 0 ;
			int number = 0;
			String goodName = "";
			String goodPrice = "";
			String goodUnit = "";
			for(OrderInfo orderInfo:orderInfoList){
				imgurl = "";
				alias = "";
				goodName = "";
				gender = 0;
				number = 0;
				goodUnit = "";
				order = new Order();
				order.setOrderSn(orderInfo.getOrderSn());
				order.setStatus(orderInfo.getOrderStatus());
				order.setOrderTime(fullSdf.format(orderInfo.getCreateTime()));
				
				//根据会员id获取用户信息
				order.setImgurl(imgurl);
				order.setAlias(alias);
				order.setGender(gender);
				
				//根据订单id获取订单商品信息
				order.setGoodName(goodName);
				order.setNumber(number);
				order.setGoodPrice(goodPrice);
				order.setGoodUnit(goodUnit);
				result.add(order);
			}
		}else{
			orderInfoList = Collections.emptyList();
		}
		
		code = ResultCodeEnum.SUCCESS;
		return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
	}
	
	/**
	 * 查看订单详情
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "order/order_detail", method = RequestMethod.POST)
	public  ResponseMessage<?>  orderDetail(){
		boolean success =false;
		ResultCodeEnum code = ResultCodeEnum.ERROR;
		String orderSn = request.getParameter("orderSn");
		String optionStr = request.getParameter("option");
		String memberId = null;//拦截器根据token，会员名称获取会员id并输入至memberId

		Order result = null ;
		
		if(StringUtils.isEmpty(orderSn)){
			code = ResultCodeEnum.PARD_BREAK;
			logger.info("orderSn isEmpty");
			return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
		}
		
		int option = 0;
		if(StringUtils.isEmpty(optionStr)){
			code = ResultCodeEnum.PARD_BREAK;
			logger.info("option isEmpty");
			return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
		}else{
			try{
				option = Integer.parseInt(optionStr);
				if( !(option ==1 || option ==2) ){
					throw new RuntimeException();
				}
			}catch(Exception e){
				e.printStackTrace();
				code = ResultCodeEnum.PARD_BREAK;
				logger.info("option PARD_BREAK");
				return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
			}
		}
		
		long memberid = 0 ;
		if(StringUtils.isEmpty(memberId)){
			code = ResultCodeEnum.PARD_BREAK;
			logger.info("memberId isEmpty");
			return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
		}else{
			try{
				memberid = Long.parseLong(memberId);
			}catch(Exception e){
				e.printStackTrace();
				code = ResultCodeEnum.PARD_BREAK;
				logger.info("memberId parseLong error");
				return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
			}
		}
		
		OrderInfo orderInfo = null;
		if(option == 1){
			orderInfo = orderService.getMemberOrder(memberid, orderSn) ;
		}else{
			orderInfo = orderService.getSallOrder(memberid, orderSn);
		}
				
		//根据会员id、订单号查询会员订单
		if(orderInfo == null){
			code = ResultCodeEnum.PARD_BREAK;
			logger.info("orderSn error");
			return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
		}
		success = true;
		code = ResultCodeEnum.SUCCESS;
		return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
	}
	
	/**
	 * 删除订单 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "order/delete_order", method = RequestMethod.POST)
	public  ResponseMessage<?>  orderDelete(){
		boolean success = false;
		ResultCodeEnum code = ResultCodeEnum.ERROR;
		String msg = null;
		Object result = null ;
		
		String orderSn = request.getParameter("orderSn");
		String optionStr  = request.getParameter("option");
		String memberIdStr = null;
		
		if(StringUtils.isEmpty(orderSn)){
			code = ResultCodeEnum.PARD_BREAK;
			logger.info("orderSn isEmpty");
			return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
		}
		int option = 0;
		if(StringUtils.isEmpty(optionStr)){
			code = ResultCodeEnum.PARD_BREAK;
			logger.info("option isEmpty");
			return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
		}else{
			try{
				option = Integer.parseInt(orderSn);
				if( !(option == 1 || option == 2) ){
					throw new RuntimeException();
				}
			}catch(Exception e){
				code = ResultCodeEnum.PARD_BREAK;
				logger.info("option parseInt error");
				return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
			}
		}
		long memberId = 0 ;
		if(StringUtils.isEmpty(memberIdStr)){
			code = ResultCodeEnum.PARD_BREAK;
			logger.info("memberId isEmpty");
			return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
		}else{
			try{
				memberId = Long.parseLong(memberIdStr);
				if(memberId<0){
					throw new RuntimeException();
				}
			}catch(Exception e){
				e.printStackTrace();
				code = ResultCodeEnum.PARD_BREAK;
				logger.info("memberId ");
				return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
			}
		}
		
		
		if( option == 1 ){
			//删除 买家订单
			success = orderService.removeMemberOrder(memberId, orderSn);
		}else if( option ==2 ){
			//删除 卖家订单
			success = orderService.removeSallOrder(memberId, orderSn);
		}
		
		if(success){
			code = ResultCodeEnum.SUCCESS;
		}
		return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
	}
	
	/**
	 * 取消订单
	 * @return
	 */
	@RequestMapping(value = "order/cancel_order", method = RequestMethod.POST)
	public  ResponseMessage<?>  orderCancel(){
		boolean success = false;
		ResultCodeEnum code = ResultCodeEnum.ERROR;
		String msg = null;
		Object result = null ;
		
		String orderSn = request.getParameter("orderSn");
		String memberId = null;
		String reason = request.getParameter("reason");
		String optionStr = request.getParameter("option");
		
		
		if( StringUtils.isEmpty(orderSn)){
			code = ResultCodeEnum.PARD_BREAK;
			logger.info("orderSn isEmpty");
			return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
		}
		if( StringUtils.isEmpty(memberId) ){
			code = ResultCodeEnum.PARD_BREAK;
			logger.info("memberId isEmpty");
			return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
		}
		if( StringUtils.isEmpty(reason) ){
			code = ResultCodeEnum.PARD_BREAK;
			logger.info("reason isEmpty");
			return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
		}
		int option = 0 ;
		if( StringUtils.isEmpty(optionStr) ){
			code = ResultCodeEnum.PARD_BREAK;
			logger.info("option isEmpty");
			return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
		}else{
			try{
				option = Integer.parseInt(optionStr);
				if( !(option == 1 ||  option == 2) ){
					throw new RuntimeException();
				}
			}catch(Exception e){
				e.printStackTrace();
				code = ResultCodeEnum.PARD_BREAK;
				logger.info("option PARD_BREAK");
				return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
			}
			
		}
		
		//取消订单
		if(option == 1){
			result = orderService.cancelMemberOrder(Long.parseLong(memberId), orderSn);
		}else if(option == 2){
			result = orderService.cancelSallOrder(Long.parseLong(memberId), orderSn);
		}
		if(success){
			code = ResultCodeEnum.SUCCESS;
		}
		return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
	}
	
	final SimpleDateFormat daySdf = new SimpleDateFormat("yyyy-MM-dd");
	/**
	 * 简介: 提交订单
	 * @author zhaowei
	 * @Date 2015年12月21日 上午11:07:34 
	 * @version 1.0
	 */
	@RequestMapping(value = "order/submit_order", method = RequestMethod.POST)
	public  ResponseMessage<?>  orderSubmit(){
		boolean success = false;
		ResultCodeEnum code = ResultCodeEnum.ERROR;
		String msg = null;
		Object result = null ;
		
		String goodsSn = request.getParameter("goodsSn");
		String addressIdStr = request.getParameter("addressId");
		String time = request.getParameter("time");
		String numberStr = request.getParameter("number");
		String remarks = request.getParameter("remarks");
		String memberId = null ;
		
		int addressId = 0 ;
		if(StringUtils.isEmpty(addressIdStr)){
			code = ResultCodeEnum.PARD_BREAK;
			logger.info("addressId isEmpty");
			return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
		}else{
			try{
				addressId = Integer.parseInt(addressIdStr);
			}catch(Exception e){
				e.printStackTrace();
				code = ResultCodeEnum.PARD_BREAK;
				logger.info("addressId parseInt error");
				return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
			}
		}
		int number = 0;
		if(StringUtils.isEmpty(numberStr)){
			code = ResultCodeEnum.PARD_BREAK;
			logger.info("number isEmpty");
			return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
		}else{
			try{
				number = Integer.parseInt(numberStr);
			}catch(Exception e){
				e.printStackTrace();
				code = ResultCodeEnum.PARD_BREAK;
				logger.info("number parseInt error");
				return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
			}
		}
		Date timeDate = null ;
		if(StringUtils.isEmpty(time)){
			code = ResultCodeEnum.PARD_BREAK;
			logger.info("time isEmpty");
			return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
		}else{
			try {
				timeDate = daySdf.parse(time);
			} catch (ParseException e) {
				e.printStackTrace();
				code = ResultCodeEnum.PARD_BREAK;
				logger.info("time parse error");
				return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
			}
		}
		
		if(StringUtils.isEmpty(memberId)){
			code = ResultCodeEnum.PARD_BREAK;
			logger.info("memberId isEmpty");
			return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
		}
		
		Goods goods = null ;
		if(StringUtils.isEmpty(goodsSn)){
			code = ResultCodeEnum.PARD_BREAK;
			logger.info("goodsSn isEmpty");
			return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
		}else{
			//TODO:判断时间段是否可用 V1.0简单做，不判断。可下重复的订单
			//判断产品是否存在
			goods = goodsService.selectGoodsByGoodsId(goodsSn);
			if(goods == null){
				code = ResultCodeEnum.PARD_BREAK;
				logger.info("goodsSn not exist");
				return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
			}
		}
		//提交订单
		Order order = new Order();
		order.setGoods(goods);
		order.setAddressId(addressId);
		order.setTime(timeDate);
		order.setNumber(number);
		order.setRemarks(remarks);
		order.setMemberid(Long.parseLong(memberId));
		success = orderService.submitOrderInfo(order);
		if(success){
			code = ResultCodeEnum.SUCCESS;
		}
		return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
	}
	
	/**
	 * 提交订单评价
	 * @return
	 */
	@RequestMapping(value = "order/submit_evaluate", method = RequestMethod.POST)
	public  ResponseMessage<?>  orderEvaluate(){
		boolean success = false;
		ResultCodeEnum code = ResultCodeEnum.ERROR;
		Object result = null ;
		
		String orderSn = request.getParameter("orderSn");
		String describeStr = request.getParameter("describe");
		String qualityStr = request.getParameter("quality");
		String attitudeStr = request.getParameter("attitude");
		String tags = request.getParameter("tags");
		String detailed = request.getParameter("detailed");
		String imgs = request.getParameter("imgs");
		String memberId = null;
		
		if(StringUtils.isEmpty(memberId)){
			logger.info("memberId isEmpty");
			return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
		}
		
		if(StringUtils.isEmpty(orderSn)){
			logger.info("orderSn isEmpty");
			return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
		}else{
			boolean isExist = false;
			//TODO:订单是否存在
			if(!isExist){
				logger.info("orderSn not Exist");
				return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
			}
		}
		
		int describe = 0 ;
		if(StringUtils.isEmpty(describeStr)){
			logger.info("describe isEmpty");
			return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
		}else{
			try{
				describe = Integer.parseInt(describeStr);
				if(describe<0){
					logger.info("describe < 0");
					return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
				}
			}catch(Exception e){
				logger.info("describe parseInt error");
				return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
			}
		}
		
		int quality = 0 ;
		if(StringUtils.isEmpty(qualityStr)){
			logger.info("quality isEmpty");
			return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
		}else{
			try{
				quality = Integer.parseInt(qualityStr);
				if(quality<0){
					logger.info("quality < 0");
					return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
				}
			}catch(Exception e){
				logger.info("quality parseInt error");
				return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
			}
		}
		
		int attitude = 0 ;
		if(StringUtils.isEmpty(attitudeStr)){
			logger.info("attitude isEmpty");
			return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
		}else{
			try{
				attitude = Integer.parseInt(attitudeStr);
				if(attitude<0){
					logger.info("attitude < 0");
					return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
				}
			}catch(Exception e){
				logger.info("attitude parseInt error");
				return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
			}
		}
		
		//TODO:新增订单评论
		OrderCommentDto orderComment = new OrderCommentDto();
		orderComment.setOrderSn(orderSn);
		orderComment.setDescribe(describe);
		orderComment.setQuality(quality);
		orderComment.setAttitude(attitude);
		orderComment.setTags(tags);
		orderComment.setDetailed(detailed);
		orderComment.setImgsIds(imgs);
		success = orderService.saveOrderComment(orderComment);
		if(success){
			code = ResultCodeEnum.SUCCESS;
		}
		
		return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
	}
	
	/**
	 * 订单评价列表
	 * 简介:
	 * @author zhaowei
	 * @Date 2015年12月21日 下午1:53:25 
	 * @version 1.0
	 */
	@RequestMapping(value = "order/evaluate_list", method = RequestMethod.POST)
	public  ResponseMessage<?>  orderEvaluateList(){
		boolean success = false;
		ResultCodeEnum code = ResultCodeEnum.ERROR;
		List<OrderCommentDto> result = null ;
		
		String orderSn = request.getParameter("orderSn");
		String pageStr  = request.getParameter("page");
		String rowsStr = request.getParameter("rows");
		
		if(StringUtils.isEmpty(orderSn)){
			logger.info("orderSn isEmpty");
			return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
		}
		
		int page = 1;
		int rows = 10;
		if(!StringUtils.isEmpty(pageStr)){
			try{
				page = Integer.parseInt(pageStr);
				page = page <=0 ? 1 : page;
			}catch(Exception e){
				logger.info("page parseInt error");
			}
		}
		if(!StringUtils.isEmpty(rowsStr)){
			try{
				rows = Integer.parseInt(rowsStr);
				rows = rows <=0 ? rows = 1 : rows;
			}catch(Exception e){
				logger.info("rows parseInt error");
			}
		}
		
		OrderCommentDto orderCommentDto = new OrderCommentDto();
		orderCommentDto.setOrderSn(orderSn);
		result = orderCommentService.findOrderCommentList(orderCommentDto, page, rows);
		code = ResultCodeEnum.SUCCESS;
		return ResponseUtils.jsonResult(result, success, code.getValue(), code.getMsg());
	}
	
	
	
}
